package com.itheima.service.impl;


import cn.hutool.core.util.IdUtil;
import com.itheima.common.ThreadLocalIUtil;
import com.itheima.dto.ShoppingCartDto;
import com.itheima.dto.SubShoppingDto;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.pojo.ShoppingCart;
import com.itheima.pojo.User;
import com.itheima.service.ShoppingCartService;
import com.itheima.service.UserService;
import com.itheima.vo.ShoppingCartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserService userService;

    @Override
    public boolean add(ShoppingCartDto shoppingCartDto) {
        ShoppingCart shoppingCart=new ShoppingCart();



        String id = IdUtil.getSnowflakeNextIdStr();
        shoppingCart.setId(id);
        shoppingCart.setUserId(ThreadLocalIUtil.getId());
        log.info("生成的UserId是：{}",ThreadLocalIUtil.getId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        //找到用户名
        User user = userService.findById(ThreadLocalIUtil.getId());
        shoppingCart.setCreateUser( user.getName());
        BeanUtils.copyProperties(shoppingCartDto,shoppingCart);
        if (shoppingCartDto.getNumber()==null){
            shoppingCart.setNumber(1);
        }
        //  测试时 userId默认为001，number默认为1
        // shoppingCart.setUserId("001");
        // shoppingCart.setNumber(1);
        int add = shoppingCartMapper.add(shoppingCart);
        return add>0;
    }

    @Override
    public List<ShoppingCartVo> getList() {

        List<ShoppingCart> list = shoppingCartMapper.getList();
        List<ShoppingCartVo> listVo=new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            ShoppingCartVo shoppingCartVo=new ShoppingCartVo();
            BeanUtils.copyProperties(shoppingCart,shoppingCartVo);
            listVo.add(shoppingCartVo);

        }

        return  listVo;

    }

    @Override
    public boolean clean() {

        int clean = shoppingCartMapper.clean();
        return  clean>0;
    }

    @Override
    public boolean sub(SubShoppingDto subShoppingDto) {
        String dishId = subShoppingDto.getDishId();
        String setmealId = subShoppingDto.getSetmealId();
        int delete = shoppingCartMapper.delete(dishId, setmealId);
      return   delete>0;
    }
}
